package com.example.spring.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.spring.demo.common.error.CustomException;
import com.example.spring.demo.common.model.req.CollectParam;
import com.example.spring.demo.entity.Goods;
import com.example.spring.demo.entity.GoodsCollect;
import com.example.spring.demo.service.GoodsCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2024/12/31 10:51
 **/
@RequestMapping("/api/collect")
@RestController
public class GoodsCollectController {
    @Autowired
    private GoodsCollectService goodsCollectService;
    //收藏
    @PostMapping("/collect")
    public String collect(@RequestBody GoodsCollect goodsCollect){
        //判断是否已经收藏
        QueryWrapper<GoodsCollect> query = new QueryWrapper<>();
        query.lambda().eq(GoodsCollect::getGoodsId,goodsCollect.getGoodsId())
                .eq(GoodsCollect::getUserId,goodsCollect.getUserId());
        GoodsCollect one = goodsCollectService.getOne(query);
        if(one == null){ //未收藏
            goodsCollect.setCollectTime(new Date());
            if(goodsCollectService.save(goodsCollect)){
                return "收藏成功!";
            }
            throw new CustomException("收藏失败!");
        }else{ //已收藏,取消收藏
            if(goodsCollectService.remove(query)){
                return "取消收藏!";
            }
            throw new CustomException("取消收藏失败!");
        }
    }

    //判断是否已经收藏
    @GetMapping("/hasCollect")
    public String hasCollect(GoodsCollect goodsCollect){
        //判断是否已经收藏
        QueryWrapper<GoodsCollect> query = new QueryWrapper<>();
        query.lambda().eq(GoodsCollect::getGoodsId,goodsCollect.getGoodsId())
                .eq(GoodsCollect::getUserId,goodsCollect.getUserId());
        GoodsCollect one = goodsCollectService.getOne(query);
        if(one != null){ //已经收藏
            return "1";
        }else{ //未收藏
            return "0";
        }
    }

    //小程序我的收藏列表
    @GetMapping("/getMyCollect")
    public IPage<Goods> getMyCollect(CollectParam param){
        return goodsCollectService.getMyCollect(param);
    }

    //取消收藏
    @PostMapping("/cancel")
    public String cancel(@RequestBody GoodsCollect collect){
        if(goodsCollectService.removeById(collect.getCollectId())){
            return "取消成功!";
        }
        throw new CustomException("取消失败!");
    }

}